package controller

import (
	"github.com/cn-ygf/go-admin/internal/action"
	"github.com/cn-ygf/go-admin/internal/modular/system/model"
	"github.com/cn-ygf/go-admin/internal/modular/system/service"
	"github.com/cn-ygf/go-admin/internal/modular/system/vo"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
	"github.com/mojocn/base64Captcha"
)

type LoginController struct {
	Ctx iris.Context
}

func (c *LoginController) Post(req vo.LoginReq) mvc.Result {
	var (
		err  error
		user *model.SysUser
	)
	captchaEnabledValue := service.ConfigService.Get("sys.account.captchaEnabled")
	if captchaEnabledValue != nil {
		if captchaEnabledValue.ConfigValue == "true" {
			// 验证码校验
			if !captcha.store.Verify(req.UUID, req.Code, true) {
				return action.Error("验证码错误")
			}
		}
	}
	user, err = service.LoginService.Login(req.Username, req.Password)
	if err != nil {
		service.LoginLogService.Add(req.Username, "1", err.Error(), c.Ctx)
		return action.Error(err.Error())
	}

	token, err := service.LoginService.GenerateToken(user)
	if err != nil {
		systemLog.Errorln(err.Error())
		return action.ServerError()
	}
	service.LoginLogService.Add(req.Username, "0", "登录成功", c.Ctx)
	return action.Data(map[string]any{"token": token})
}

type sCaptcha struct {
	driver *base64Captcha.DriverString
	store  base64Captcha.Store
}

var (
	captcha = sCaptcha{
		driver: &base64Captcha.DriverString{
			Height:          80,
			Width:           240,
			NoiseCount:      50,
			ShowLineOptions: 20,
			Length:          4,
			Source:          "abcdefghjkmnpqrstuvwxyz23456789",
			Fonts:           []string{"chromohv.ttf"},
		},
		store: base64Captcha.DefaultMemStore,
	}
)

// GetCaptcha 后台登录验证码
func (c *LoginController) GetCaptcha() mvc.Result {
	result := map[string]any{
		"img":            "",
		"captchaEnabled": false,
		"uuid":           "",
	}
	captchaEnabledValue := service.ConfigService.Get("sys.account.captchaEnabled")
	if captchaEnabledValue != nil {
		if captchaEnabledValue.ConfigValue == "true" {
			driver := captcha.driver.ConvertFonts()
			a := base64Captcha.NewCaptcha(driver, captcha.store)
			id, imgString, err := a.Generate()
			if err != nil {
				systemLog.Errorf(err.Error())
				return action.ServerError()
			}
			result["img"] = imgString
			result["captchaEnabled"] = true
			result["uuid"] = id
		}
	}
	return action.Data(result)
}

func (c *LoginController) PostLogout() mvc.Result {
	service.LoginService.ClearToken(c.Ctx)
	return action.OK()
}
